<?php
class Manager_Category
{
	/**
	 * All categories representation
	 * @var string
	 */
	const CATEGORY_DEFAULT = 'all';
	
	protected function __construct()
	{	
	}

	public static function initialize()
	{
		$names = array(self::CATEGORY_DEFAULT);
		
		$criteria = new Criteria();
		
		try {
			foreach ($names as $name) {
				$criteria->clear();
				$criteria->add(CategoriesPeer::NAME, $name, Criteria::EQUAL);
				
				if (CategoriesPeer::doCount($criteria) === 0) {
					// add to database missing reqest statuses
					$category = new Categories();
					$category->setName($name);
					$category->save();
				}
			}
		} catch (Exception $e) {
			throw new Exception('Categories could not be initialized in the DB. ' . $e->getMessage());
		}
	}
	
	public static function getDefault()
	{
		$criteria = new Criteria();
		$criteria->add(CategoriesPeer::NAME, self::CATEGORY_DEFAULT, Criteria::EQUAL);
		
		$default = CategoriesPeer::doSelectOne($criteria);
		
		if (empty($default)) {
			self::initialize();
		}
		
		$default = CategoriesPeer::doSelectOne($criteria);
		
		if (empty($default)) {
			throw new Exception('Default category could not be read.');
		}
		
		return $default;
	}
	
	public static function isInDatabase($category)
	{
		$criteria = new Criteria();
		$criteria->add(CategoriesPeer::NAME, $category->getName(), Criteria::EQUAL);
		return false;
		$category = CategoriesPeer::doSelect($criteria);
		//var_dump ($category);
		return (!empty($category));
	}
	
	public static function getTags(Categories $category)
	{
		$tags = array();
		
		$criteria = new Criteria();
		$criteria->add(CategoriesPeer::ID_CATEGORY, $category->getIdCategory(), Criteria::EQUAL);
		$categoryTags = CategoriestagsPeer::doSelect($criteria);
		
		foreach ($categoryTags as $catTag) {
			$tags[] = TagsPeer::retrieveByPK($catTag->getIdTag()); 
		}
		
		return $tags;
	}
	
	public static function setTags(Categories $category, array $tags = array())
	{
		foreach ($tags as $tag) {
			$catTag = new Categoriestags();
			$catTag->setCategories($category)
				->setTags($tag)
				->save();
		}
	}
}